package view.student;

import controller.UserController;
import controller.AttendanceController;
import model.User;
import model.AttendanceRecord;
import model.CreditLog;
import dao.AttendanceDAO.CheckInResult;
import dao.AttendanceDAO.CheckOutResult;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.swing.Timer;

/**
 * 个人信息面板
 */
public class PersonalInfoPanel extends JPanel {
    private User currentUser;
    private UserController userController;
    private AttendanceController attendanceController;

    private JTextField nameField;
    private JTextField phoneField;
    private JTextField emailField;
    private JPasswordField oldPasswordField;
    private JPasswordField newPasswordField;
    private JPasswordField confirmPasswordField;

    private JButton updateInfoButton;
    private JButton changePasswordButton;

    // 信誉分和考勤相关组件
    private JLabel creditScoreLabel;
    private JLabel creditLevelLabel;
    private JProgressBar creditProgressBar;
    private JPanel todayAttendancePanel;
    private JButton refreshButton;
    private JPanel creditHistoryContainer; // 保存历史记录容器的引用

    public PersonalInfoPanel(User user) {
        this.currentUser = user;
        this.userController = new UserController();
        this.attendanceController = new AttendanceController();

        initComponents();
        setupLayout();
        setupEventListeners();
        loadUserInfo();
        loadCreditAndAttendanceInfo();

        // 设置定时器，每30秒刷新一次考勤状态
        Timer refreshTimer = new Timer(30000, e -> loadCreditAndAttendanceInfo());
        refreshTimer.start();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        setBackground(new Color(248, 250, 252));

        nameField = new JTextField();
        phoneField = new JTextField();
        emailField = new JTextField();
        oldPasswordField = new JPasswordField();
        newPasswordField = new JPasswordField();
        confirmPasswordField = new JPasswordField();

        updateInfoButton = new JButton("更新个人信息");
        changePasswordButton = new JButton("修改密码");
        refreshButton = new JButton("刷新数据");

        // 初始化信誉分和考勤组件
        creditScoreLabel = new JLabel("100");
        creditLevelLabel = new JLabel("良好");
        creditProgressBar = new JProgressBar(0, 150);
        creditProgressBar.setValue(100);
        creditProgressBar.setStringPainted(true);
        todayAttendancePanel = new JPanel();

        // 美化组件
        styleTextField(nameField);
        styleTextField(phoneField);
        styleTextField(emailField);
        styleTextField(oldPasswordField);
        styleTextField(newPasswordField);
        styleTextField(confirmPasswordField);

        styleModernButton(updateInfoButton, new Color(99, 102, 241));
        styleModernButton(changePasswordButton, new Color(34, 197, 94));
        styleModernButton(refreshButton, new Color(34, 197, 94));
    }

    private void setupLayout() {
        // 主容器 - 渐变背景
        JPanel mainContainer = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 创建渐变背景
                GradientPaint gradient = new GradientPaint(
                        0, 0, new Color(247, 250, 255),
                        0, getHeight(), new Color(240, 245, 255));
                g2d.setPaint(gradient);
                g2d.fillRect(0, 0, getWidth(), getHeight());
            }
        };

        mainContainer.setLayout(new BorderLayout());

        // 顶部标题栏
        JPanel headerPanel = createModernHeaderPanel();

        // 主要内容区域 - 两列等宽布局
        JPanel contentPanel = new JPanel(new GridLayout(1, 2, 30, 0));
        contentPanel.setOpaque(false);
        contentPanel.setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));

        // 个人资料卡片（包含修改密码功能）
        JPanel personalInfoCard = createEnhancedPersonalInfoCard();

        // 信誉分和历史记录卡片
        JPanel creditAndHistoryCard = createCreditAndHistoryCard();

        contentPanel.add(personalInfoCard);
        contentPanel.add(creditAndHistoryCard);

        mainContainer.add(headerPanel, BorderLayout.NORTH);
        mainContainer.add(contentPanel, BorderLayout.CENTER);

        // 添加滚动支持
        JScrollPane scrollPane = new JScrollPane(mainContainer);
        scrollPane.setBorder(BorderFactory.createEmptyBorder());
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
        scrollPane.getViewport().setBackground(new Color(247, 250, 255));

        add(scrollPane, BorderLayout.CENTER);
    }

    private JPanel createModernHeaderPanel() {
        JPanel headerPanel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 渐变背景
                GradientPaint gradient = new GradientPaint(0, 0, Color.WHITE, 0, getHeight(), new Color(248, 252, 255));
                g2d.setPaint(gradient);
                g2d.fillRect(0, 0, getWidth(), getHeight());

                // 底部分割线
                g2d.setColor(new Color(226, 232, 240));
                g2d.drawLine(0, getHeight() - 1, getWidth(), getHeight() - 1);
            }
        };

        headerPanel.setLayout(new BorderLayout());
        headerPanel.setBorder(BorderFactory.createEmptyBorder(25, 30, 25, 30));

        // 左侧：标题和描述
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setOpaque(false);

        JLabel titleLabel = new JLabel("👤 个人中心");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
        titleLabel.setForeground(new Color(30, 41, 59));

        JLabel subLabel = new JLabel("管理您的基本信息和信誉分记录");
        subLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        subLabel.setForeground(new Color(100, 116, 139));

        leftPanel.add(titleLabel, BorderLayout.NORTH);
        leftPanel.add(subLabel, BorderLayout.CENTER);

        // 右侧：刷新按钮
        JPanel rightPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 0, 0));
        rightPanel.setOpaque(false);
        rightPanel.add(refreshButton);

        headerPanel.add(leftPanel, BorderLayout.WEST);
        headerPanel.add(rightPanel, BorderLayout.EAST);

        return headerPanel;
    }

    private JLabel createFieldLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        label.setForeground(new Color(107, 114, 128));
        label.setAlignmentX(Component.LEFT_ALIGNMENT);
        return label;
    }

    private void setupEventListeners() {
        updateInfoButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleUpdateInfo();
            }
        });

        changePasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                handleChangePassword();
            }
        });

        refreshButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                refreshData();
            }
        });
    }

    private void loadUserInfo() {
        nameField.setText(currentUser.getName());
        phoneField.setText(currentUser.getPhone());
        emailField.setText(currentUser.getEmail());
    }

    private void handleUpdateInfo() {
        try {
            String name = nameField.getText().trim();
            String phone = phoneField.getText().trim();
            String email = emailField.getText().trim();

            if (name.isEmpty()) {
                JOptionPane.showMessageDialog(this, "姓名不能为空!", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            currentUser.setName(name);
            currentUser.setPhone(phone);
            currentUser.setEmail(email);

            boolean success = userController.updateUser(currentUser);

            if (success) {
                JOptionPane.showMessageDialog(this, "个人信息更新成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "更新失败!", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "更新失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    private void handleChangePassword() {
        try {
            String oldPassword = new String(oldPasswordField.getPassword());
            String newPassword = new String(newPasswordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());

            if (oldPassword.isEmpty() || newPassword.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写完整的密码信息!", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!newPassword.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(this, "新密码两次输入不一致!", "提示", JOptionPane.WARNING_MESSAGE);
                return;
            }

            if (!oldPassword.equals(currentUser.getPassword())) {
                JOptionPane.showMessageDialog(this, "原密码错误!", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            currentUser.setPassword(newPassword);
            boolean success = userController.updateUser(currentUser);

            if (success) {
                JOptionPane.showMessageDialog(this, "密码修改成功!", "成功", JOptionPane.INFORMATION_MESSAGE);
                // 清空密码字段
                oldPasswordField.setText("");
                newPasswordField.setText("");
                confirmPasswordField.setText("");
            } else {
                JOptionPane.showMessageDialog(this, "密码修改失败!", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "密码修改失败: " + e.getMessage(),
                    "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 美化文本框样式
     */
    private void styleTextField(JTextField textField) {
        textField.setPreferredSize(new Dimension(200, 40));
        textField.setMaximumSize(new Dimension(200, 40));
        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        textField.setBackground(new Color(255, 255, 255));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(10, 12, 10, 12)));
        textField.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 聚焦时的边框效果
        textField.addFocusListener(new java.awt.event.FocusListener() {
            @Override
            public void focusGained(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(59, 130, 246), 2),
                        BorderFactory.createEmptyBorder(9, 11, 9, 11)));
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                        BorderFactory.createEmptyBorder(10, 12, 10, 12)));
            }
        });
    }

    /**
     * 美化按钮样式
     */
    /**
     * 现代化按钮样式（与统计页面一致）
     */
    private void styleModernButton(JButton button, Color backgroundColor) {
        button.setPreferredSize(new Dimension(130, 38));
        button.setMaximumSize(new Dimension(130, 38));
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }

    private JPanel createPersonalInfoCard() {
        JPanel card = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 背景渐变
                GradientPaint gradient = new GradientPaint(
                        0, 0, Color.WHITE,
                        0, getHeight(), new Color(252, 252, 255));
                g2d.setPaint(gradient);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 16, 16);

                // 阴影
                g2d.setColor(new Color(0, 0, 0, 8));
                g2d.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 16, 16);
            }
        };

        card.setLayout(new BorderLayout(0, 20));
        card.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));

        // 标题栏
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);

        JLabel titleLabel = new JLabel("📝 个人资料");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(30, 41, 59));

        JLabel descLabel = new JLabel("编辑您的基本信息");
        descLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        descLabel.setForeground(new Color(100, 116, 139));

        JPanel titleContainer = new JPanel(new BorderLayout());
        titleContainer.setOpaque(false);
        titleContainer.add(titleLabel, BorderLayout.NORTH);
        titleContainer.add(descLabel, BorderLayout.CENTER);

        headerPanel.add(titleContainer, BorderLayout.WEST);

        // 表单区域
        JPanel formPanel = new JPanel();
        formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
        formPanel.setOpaque(false);

        // 学号（只读）
        JPanel studentIdPanel = createModernFieldPanel("学号", currentUser.getStudentId(), true);

        // 姓名
        JPanel namePanel = createModernFieldPanel("姓名", "", false);
        namePanel.add(nameField);

        // 电话
        JPanel phonePanel = createModernFieldPanel("电话", "", false);
        phonePanel.add(phoneField);

        // 邮箱
        JPanel emailPanel = createModernFieldPanel("邮箱", "", false);
        emailPanel.add(emailField);

        formPanel.add(studentIdPanel);
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(namePanel);
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(phonePanel);
        formPanel.add(Box.createVerticalStrut(20));
        formPanel.add(emailPanel);
        formPanel.add(Box.createVerticalStrut(20));

        // 按钮紧凑放置
        updateInfoButton.setText("保存修改");
        updateInfoButton.setAlignmentX(Component.LEFT_ALIGNMENT);
        formPanel.add(updateInfoButton);

        card.add(headerPanel, BorderLayout.NORTH);
        card.add(formPanel, BorderLayout.CENTER);

        return card;
    }

    private JPanel createLoginInfoCard() {
        JPanel card = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 背景渐变
                GradientPaint gradient = new GradientPaint(
                        0, 0, Color.WHITE,
                        0, getHeight(), new Color(252, 252, 255));
                g2d.setPaint(gradient);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 16, 16);

                // 阴影
                g2d.setColor(new Color(0, 0, 0, 8));
                g2d.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 16, 16);
            }
        };

        card.setLayout(new BorderLayout(0, 15));
        card.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
        card.setPreferredSize(new Dimension(0, 200));

        // 标题栏
        JLabel titleLabel = new JLabel("🔐 登录信息");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        titleLabel.setForeground(new Color(30, 41, 59));

        // 信息列表
        JPanel infoPanel = new JPanel();
        infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
        infoPanel.setOpaque(false);

        // 用户名
        JPanel usernamePanel = createCompactInfoPanel("👤", "用户名", currentUser.getStudentId());

        // 电话
        String phone = currentUser.getPhone() != null ? currentUser.getPhone() : "未设置";
        JPanel phonePanel = createCompactInfoPanel("📱", "电话", phone);

        // 用户角色
        String role = currentUser.getUserType() == 1 ? "管理员" : "学生";
        JPanel rolePanel = createCompactInfoPanel("🎭", "用户角色", role);

        infoPanel.add(usernamePanel);
        infoPanel.add(Box.createVerticalStrut(12));
        infoPanel.add(phonePanel);
        infoPanel.add(Box.createVerticalStrut(12));
        infoPanel.add(rolePanel);

        card.add(titleLabel, BorderLayout.NORTH);
        card.add(infoPanel, BorderLayout.CENTER);

        return card;
    }

    private JPanel createPasswordCard() {
        JPanel card = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 背景渐变
                GradientPaint gradient = new GradientPaint(
                        0, 0, Color.WHITE,
                        0, getHeight(), new Color(252, 252, 255));
                g2d.setPaint(gradient);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 16, 16);

                // 阴影
                g2d.setColor(new Color(0, 0, 0, 8));
                g2d.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 16, 16);
            }
        };

        card.setLayout(new BorderLayout(0, 15));
        card.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 标题栏
        JLabel titleLabel = new JLabel("🔑 修改密码");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 16));
        titleLabel.setForeground(new Color(30, 41, 59));

        // 表单区域
        JPanel formPanel = new JPanel();
        formPanel.setLayout(new BoxLayout(formPanel, BoxLayout.Y_AXIS));
        formPanel.setOpaque(false);

        // 原密码
        JLabel oldPwdLabel = createCompactFieldLabel("原密码");
        formPanel.add(oldPwdLabel);
        formPanel.add(Box.createVerticalStrut(5));
        formPanel.add(oldPasswordField);
        formPanel.add(Box.createVerticalStrut(12));

        // 新密码
        JLabel newPwdLabel = createCompactFieldLabel("新密码");
        formPanel.add(newPwdLabel);
        formPanel.add(Box.createVerticalStrut(5));
        formPanel.add(newPasswordField);
        formPanel.add(Box.createVerticalStrut(12));

        // 确认密码
        JLabel confirmPwdLabel = createCompactFieldLabel("确认密码");
        formPanel.add(confirmPwdLabel);
        formPanel.add(Box.createVerticalStrut(5));
        formPanel.add(confirmPasswordField);
        formPanel.add(Box.createVerticalStrut(15));

        // 按钮紧凑放置
        changePasswordButton.setText("修改密码");
        changePasswordButton.setAlignmentX(Component.LEFT_ALIGNMENT);
        formPanel.add(changePasswordButton);

        card.add(titleLabel, BorderLayout.NORTH);
        card.add(formPanel, BorderLayout.CENTER);

        return card;
    }

    private JPanel createFieldPanel(String labelText, String value, boolean isReadOnly) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(false);

        JLabel label = createFieldLabel(labelText);
        panel.add(label);
        panel.add(Box.createVerticalStrut(5));

        if (isReadOnly && !value.isEmpty()) {
            JTextField field = new JTextField(value);
            field.setEditable(false);
            styleTextField(field);
            field.setBackground(new Color(249, 250, 251));
            field.setForeground(new Color(107, 114, 128));
            panel.add(field);
        }

        return panel;
    }

    private JPanel createModernFieldPanel(String labelText, String value, boolean isReadOnly) {
        JPanel panel = new JPanel();
        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setOpaque(false);

        JLabel label = createFieldLabel(labelText);
        panel.add(label);
        panel.add(Box.createVerticalStrut(8));

        if (isReadOnly && !value.isEmpty()) {
            JTextField field = new JTextField(value);
            field.setEditable(false);
            styleTextField(field);
            field.setBackground(new Color(249, 250, 251));
            field.setForeground(new Color(107, 114, 128));
            panel.add(field);
        }

        return panel;
    }

    private JPanel createCompactInfoPanel(String icon, String title, String value) {
        JPanel panel = new JPanel(new BorderLayout(8, 0));
        panel.setOpaque(false);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 35));

        // 图标
        JLabel iconLabel = new JLabel(icon);
        iconLabel.setFont(new Font("Segoe UI Emoji", Font.PLAIN, 16));
        iconLabel.setPreferredSize(new Dimension(25, 25));

        // 内容
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setOpaque(false);

        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        titleLabel.setForeground(new Color(100, 116, 139));

        JLabel valueLabel = new JLabel(value);
        valueLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        valueLabel.setForeground(new Color(30, 41, 59));

        contentPanel.add(titleLabel, BorderLayout.NORTH);
        contentPanel.add(valueLabel, BorderLayout.CENTER);

        panel.add(iconLabel, BorderLayout.WEST);
        panel.add(contentPanel, BorderLayout.CENTER);

        return panel;
    }

    private JLabel createCompactFieldLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        label.setForeground(new Color(107, 114, 128));
        label.setAlignmentX(Component.LEFT_ALIGNMENT);
        return label;
    }

    private JPanel createInfoDisplayPanel(String icon, String title, String value) {
        JPanel panel = new JPanel(new BorderLayout(10, 0));
        panel.setOpaque(false);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50));

        // 图标
        JLabel iconLabel = new JLabel(icon);
        iconLabel.setFont(new Font("Segoe UI Emoji", Font.PLAIN, 18));
        iconLabel.setPreferredSize(new Dimension(30, 30));

        // 内容
        JPanel contentPanel = new JPanel(new BorderLayout());
        contentPanel.setOpaque(false);

        JLabel titleLabel = new JLabel(title);
        titleLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        titleLabel.setForeground(new Color(100, 116, 139));

        JLabel valueLabel = new JLabel(value);
        valueLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        valueLabel.setForeground(new Color(30, 41, 59));

        contentPanel.add(titleLabel, BorderLayout.NORTH);
        contentPanel.add(valueLabel, BorderLayout.CENTER);

        panel.add(iconLabel, BorderLayout.WEST);
        panel.add(contentPanel, BorderLayout.CENTER);

        return panel;
    }

    /**
     * 创建信誉分和考勤状态卡片
     */
    private JPanel createCreditAndAttendanceCard() {
        JPanel card = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 背景渐变
                GradientPaint gradient = new GradientPaint(
                        0, 0, Color.WHITE,
                        0, getHeight(), new Color(252, 252, 255));
                g2d.setPaint(gradient);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 16, 16);

                // 阴影
                g2d.setColor(new Color(0, 0, 0, 8));
                g2d.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 16, 16);
            }
        };

        card.setLayout(new BorderLayout(0, 20));
        card.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));

        // 标题栏
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);

        JLabel titleLabel = new JLabel("⭐ 信誉分与考勤状态");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(30, 41, 59));

        JLabel descLabel = new JLabel("查看您的信誉分等级和今日考勤状态");
        descLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        descLabel.setForeground(new Color(100, 116, 139));

        JPanel titleContainer = new JPanel(new BorderLayout());
        titleContainer.setOpaque(false);
        titleContainer.add(titleLabel, BorderLayout.NORTH);
        titleContainer.add(descLabel, BorderLayout.CENTER);

        headerPanel.add(titleContainer, BorderLayout.WEST);

        // 主要内容区域
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        contentPanel.setOpaque(false);

        // 信誉分状态面板
        JPanel creditPanel = createCreditStatusPanel();
        creditPanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 分隔线
        JPanel separator = new JPanel();
        separator.setPreferredSize(new Dimension(0, 1));
        separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1));
        separator.setBackground(new Color(229, 231, 235));
        separator.setBorder(BorderFactory.createEmptyBorder(15, 0, 15, 0));
        separator.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 今日考勤面板
        todayAttendancePanel.setOpaque(false);
        todayAttendancePanel.setLayout(new BoxLayout(todayAttendancePanel, BoxLayout.Y_AXIS));
        todayAttendancePanel.setAlignmentX(Component.LEFT_ALIGNMENT);

        contentPanel.add(creditPanel);
        contentPanel.add(separator);
        contentPanel.add(todayAttendancePanel);

        card.add(headerPanel, BorderLayout.NORTH);
        card.add(contentPanel, BorderLayout.CENTER);

        return card;
    }

    /**
     * 创建信誉分状态面板
     */
    private JPanel createCreditStatusPanel() {
        JPanel panel = new JPanel(new BorderLayout(0, 10));
        panel.setOpaque(false);

        // 信誉分数值和等级
        JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        scorePanel.setOpaque(false);

        creditScoreLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
        creditScoreLabel.setForeground(new Color(99, 102, 241));

        JLabel scoreText = new JLabel(" 分");
        scoreText.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        scoreText.setForeground(new Color(100, 116, 139));

        creditLevelLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        creditLevelLabel.setForeground(new Color(34, 197, 94));
        creditLevelLabel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(34, 197, 94), 1),
                BorderFactory.createEmptyBorder(2, 8, 2, 8)));

        scorePanel.add(creditScoreLabel);
        scorePanel.add(scoreText);
        scorePanel.add(Box.createHorizontalStrut(15));
        scorePanel.add(creditLevelLabel);

        // 进度条
        creditProgressBar.setPreferredSize(new Dimension(0, 8));
        creditProgressBar.setBackground(new Color(229, 231, 235));
        creditProgressBar.setForeground(new Color(99, 102, 241));
        creditProgressBar.setBorderPainted(false);

        panel.add(scorePanel, BorderLayout.NORTH);
        panel.add(creditProgressBar, BorderLayout.CENTER);

        return panel;
    }

    /**
     * 加载信誉分和考勤信息
     */
    private void loadCreditAndAttendanceInfo() {
        try {
            // 更新用户信息（包含最新的信誉分）
            User updatedUser = userController.getAllUsers().stream()
                    .filter(u -> u.getUserId() == currentUser.getUserId())
                    .findFirst()
                    .orElse(currentUser);

            // 更新信誉分显示
            int creditScore = updatedUser.getCreditScore();
            creditScoreLabel.setText(String.valueOf(creditScore));
            creditLevelLabel.setText(updatedUser.getCreditScoreLevel());

            // 设置等级颜色
            Color levelColor;
            if (creditScore >= 120)
                levelColor = new Color(34, 197, 94); // 绿色
            else if (creditScore >= 80)
                levelColor = new Color(99, 102, 241); // 蓝色
            else if (creditScore >= 50)
                levelColor = new Color(245, 158, 11); // 黄色
            else
                levelColor = new Color(239, 68, 68); // 红色

            creditLevelLabel.setForeground(levelColor);
            creditLevelLabel.setBorder(BorderFactory.createCompoundBorder(
                    BorderFactory.createLineBorder(levelColor, 1),
                    BorderFactory.createEmptyBorder(2, 8, 2, 8)));

            // 不需要再加载今日考勤状态，已改为信誉分历史记录

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载今日考勤状态
     */
    private void loadTodayAttendanceStatus() {
        try {
            todayAttendancePanel.removeAll();

            List<AttendanceRecord> todayRecords = attendanceController
                    .getUserTodayActiveAttendance(currentUser.getUserId());

            if (todayRecords.isEmpty()) {
                JLabel noRecordLabel = new JLabel("今日暂无预约");
                noRecordLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
                noRecordLabel.setForeground(new Color(156, 163, 175));
                noRecordLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
                todayAttendancePanel.add(noRecordLabel);
            } else {
                JLabel headerLabel = new JLabel("今日预约状态：");
                headerLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
                headerLabel.setForeground(new Color(75, 85, 99));
                headerLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
                headerLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
                todayAttendancePanel.add(headerLabel);

                for (AttendanceRecord record : todayRecords) {
                    JPanel recordPanel = createAttendanceRecordPanel(record);
                    recordPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
                    todayAttendancePanel.add(recordPanel);
                    todayAttendancePanel.add(Box.createVerticalStrut(5));
                }
            }

            todayAttendancePanel.revalidate();
            todayAttendancePanel.repaint();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建考勤记录面板
     */
    private JPanel createAttendanceRecordPanel(AttendanceRecord record) {
        JPanel panel = new JPanel(new BorderLayout(8, 0));
        panel.setOpaque(false);
        panel.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));

        // 座位信息
        JLabel seatLabel = new JLabel(record.getSeat().getSeatNumber() + " " + record.getSeat().getArea());
        seatLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        seatLabel.setForeground(new Color(75, 85, 99));

        // 时间信息
        String timeText = record.getScheduledStartTime().format(DateTimeFormatter.ofPattern("HH:mm")) +
                "-" + record.getScheduledEndTime().format(DateTimeFormatter.ofPattern("HH:mm"));
        JLabel timeLabel = new JLabel(timeText);
        timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        timeLabel.setForeground(new Color(107, 114, 128));

        // 操作按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        buttonPanel.setOpaque(false);

        if (!record.isCheckedIn()) {
            JButton checkInBtn = new JButton("签到");
            styleCompactButton(checkInBtn, new Color(34, 197, 94));
            checkInBtn.addActionListener(e -> handleCheckIn(record.getReservationId()));
            buttonPanel.add(checkInBtn);
        } else if (!record.isCheckedOut()) {
            JButton checkOutBtn = new JButton("签退");
            styleCompactButton(checkOutBtn, new Color(239, 68, 68));
            checkOutBtn.addActionListener(e -> handleCheckOut(record.getReservationId()));
            buttonPanel.add(checkOutBtn);
        } else {
            JLabel statusLabel = new JLabel("已完成");
            statusLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
            statusLabel.setForeground(new Color(34, 197, 94));
            buttonPanel.add(statusLabel);
        }

        // 左侧信息面板
        JPanel leftPanel = new JPanel(new BorderLayout());
        leftPanel.setOpaque(false);
        leftPanel.add(seatLabel, BorderLayout.NORTH);
        leftPanel.add(timeLabel, BorderLayout.SOUTH);

        panel.add(leftPanel, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.EAST);

        return panel;
    }

    /**
     * 处理签到
     */
    private void handleCheckIn(int reservationId) {
        try {
            CheckInResult result = attendanceController.checkIn(reservationId, currentUser.getUserId());

            if (result.isSuccess()) {
                JOptionPane.showMessageDialog(this, result.getMessage(), "签到成功", JOptionPane.INFORMATION_MESSAGE);
                loadCreditAndAttendanceInfo();
            } else {
                JOptionPane.showMessageDialog(this, result.getMessage(), "签到失败", JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "签到操作失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 处理签退
     */
    private void handleCheckOut(int reservationId) {
        try {
            CheckOutResult result = attendanceController.checkOut(reservationId, currentUser.getUserId());

            if (result.isSuccess()) {
                JOptionPane.showMessageDialog(this, result.getMessage(), "签退成功", JOptionPane.INFORMATION_MESSAGE);
                loadCreditAndAttendanceInfo();
            } else {
                JOptionPane.showMessageDialog(this, result.getMessage(), "签退失败", JOptionPane.WARNING_MESSAGE);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "签退操作失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * 设置紧凑按钮样式
     */
    private void styleCompactButton(JButton button, Color backgroundColor) {
        button.setPreferredSize(new Dimension(50, 22));
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 10));
        button.setBorder(BorderFactory.createEmptyBorder(3, 8, 3, 8));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }

    /**
     * 创建增强的个人资料卡片（包含密码修改功能）
     */
    private JPanel createEnhancedPersonalInfoCard() {
        JPanel card = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 背景渐变
                GradientPaint gradient = new GradientPaint(
                        0, 0, Color.WHITE,
                        0, getHeight(), new Color(252, 252, 255));
                g2d.setPaint(gradient);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 16, 16);

                // 阴影
                g2d.setColor(new Color(0, 0, 0, 8));
                g2d.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 16, 16);
            }
        };

        card.setLayout(new BorderLayout(0, 25));
        card.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));

        // 标题栏
        JPanel headerPanel = new JPanel(new BorderLayout());
        headerPanel.setOpaque(false);

        JLabel titleLabel = new JLabel("👤 个人资料");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(30, 41, 59));

        JLabel descLabel = new JLabel("管理您的基本信息和密码设置");
        descLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        descLabel.setForeground(new Color(100, 116, 139));

        JPanel titleContainer = new JPanel(new BorderLayout());
        titleContainer.setOpaque(false);
        titleContainer.add(titleLabel, BorderLayout.NORTH);
        titleContainer.add(descLabel, BorderLayout.CENTER);

        headerPanel.add(titleContainer, BorderLayout.WEST);

        // 主要内容区域
        JPanel mainContent = new JPanel();
        mainContent.setLayout(new BoxLayout(mainContent, BoxLayout.Y_AXIS));
        mainContent.setOpaque(false);

        // 个人信息部分
        JPanel personalInfoSection = createPersonalInfoSection();
        personalInfoSection.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 分隔线（减小边距）
        JPanel separator = new JPanel();
        separator.setPreferredSize(new Dimension(0, 1));
        separator.setMaximumSize(new Dimension(Integer.MAX_VALUE, 1));
        separator.setBackground(new Color(240, 242, 247));
        separator.setBorder(BorderFactory.createEmptyBorder(12, 0, 12, 0)); // 减小边距
        separator.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 密码修改部分
        JPanel passwordSection = createPasswordSection();
        passwordSection.setAlignmentX(Component.LEFT_ALIGNMENT);

        mainContent.add(personalInfoSection);
        mainContent.add(separator);
        mainContent.add(passwordSection);

        card.add(headerPanel, BorderLayout.NORTH);
        card.add(mainContent, BorderLayout.CENTER);

        return card;
    }

    /**
     * 创建信誉分和历史记录卡片
     */
    private JPanel createCreditAndHistoryCard() {
        JPanel card = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = (Graphics2D) g;
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

                // 背景渐变
                GradientPaint gradient = new GradientPaint(
                        0, 0, Color.WHITE,
                        0, getHeight(), new Color(252, 252, 255));
                g2d.setPaint(gradient);
                g2d.fillRoundRect(0, 0, getWidth(), getHeight(), 16, 16);

                // 阴影
                g2d.setColor(new Color(0, 0, 0, 8));
                g2d.drawRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 16, 16);
            }
        };

        card.setLayout(new BorderLayout(0, 0)); // 去掉垂直间距
        card.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));

        // 使用单一的垂直布局容器，不分header和content
        JPanel mainContent = new JPanel();
        mainContent.setLayout(new BoxLayout(mainContent, BoxLayout.Y_AXIS));
        mainContent.setOpaque(false);

        // 标题部分
        JLabel titleLabel = new JLabel("⭐ 信誉分");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        titleLabel.setForeground(new Color(30, 41, 59));
        titleLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel descLabel = new JLabel("查看您的信誉分和历史记录");
        descLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        descLabel.setForeground(new Color(100, 116, 139));
        descLabel.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 信誉分状态部分 - 极简版本
        JPanel creditSection = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        creditSection.setOpaque(false);
        creditSection.setAlignmentX(Component.LEFT_ALIGNMENT);

        JLabel creditText = new JLabel("信誉分：");
        creditText.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        creditText.setForeground(new Color(75, 85, 99));

        creditScoreLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        creditScoreLabel.setForeground(new Color(99, 102, 241));

        JLabel totalText = new JLabel("/150  |  等级：");
        totalText.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        totalText.setForeground(new Color(100, 116, 139));

        creditLevelLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 11));
        creditLevelLabel.setForeground(new Color(34, 197, 94));
        creditLevelLabel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(34, 197, 94), 1),
                BorderFactory.createEmptyBorder(1, 6, 1, 6)));

        creditSection.add(creditText);
        creditSection.add(creditScoreLabel);
        creditSection.add(totalText);
        creditSection.add(creditLevelLabel);

        creditSection.setMaximumSize(new Dimension(Integer.MAX_VALUE, 30)); // 固定高度

        // 历史记录部分（紧挨着信誉分，无分隔）
        JPanel historySection = createCreditHistorySection();
        historySection.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 按顺序添加所有组件，使用最小间距
        mainContent.add(titleLabel);
        mainContent.add(Box.createVerticalStrut(3));
        mainContent.add(descLabel);
        mainContent.add(Box.createVerticalStrut(15));
        mainContent.add(creditSection);
        mainContent.add(historySection); // 直接紧挨着，无任何间距

        card.add(mainContent, BorderLayout.CENTER);

        return card;
    }

    /**
     * 创建紧凑字段面板
     */
    private JPanel createCompactFieldPanel(String labelText, JComponent field) {
        JPanel panel = new JPanel(new BorderLayout(0, 4));
        panel.setOpaque(false);
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 50));

        JLabel label = new JLabel(labelText);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        label.setForeground(new Color(107, 114, 128));

        panel.add(label, BorderLayout.NORTH);
        panel.add(field, BorderLayout.CENTER);

        return panel;
    }

    /**
     * 创建个人信息部分
     */
    private JPanel createPersonalInfoSection() {
        JPanel section = new JPanel();
        section.setLayout(new BoxLayout(section, BoxLayout.Y_AXIS));
        section.setOpaque(false);

        // 学号（只读）
        section.add(createInfoDisplayPanel("👤", "学号", currentUser.getStudentId()));
        section.add(Box.createVerticalStrut(12));

        // 姓名（可编辑）
        nameField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32));
        nameField.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.add(createCompactFieldPanel("姓名", nameField));
        section.add(Box.createVerticalStrut(8));

        // 手机（可编辑）
        phoneField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32));
        phoneField.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.add(createCompactFieldPanel("手机", phoneField));
        section.add(Box.createVerticalStrut(8));

        // 邮箱（可编辑）
        emailField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32));
        emailField.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.add(createCompactFieldPanel("邮箱", emailField));
        section.add(Box.createVerticalStrut(15));

        // 更新按钮（增加宽度以完全显示文字）
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        buttonPanel.setOpaque(false);
        updateInfoButton.setPreferredSize(new Dimension(150, 32));
        buttonPanel.add(updateInfoButton);
        section.add(buttonPanel);

        return section;
    }

    /**
     * 创建密码修改部分
     */
    private JPanel createPasswordSection() {
        JPanel section = new JPanel();
        section.setLayout(new BoxLayout(section, BoxLayout.Y_AXIS));
        section.setOpaque(false);

        // 密码修改标题
        JLabel pwdLabel = new JLabel("修改密码：");
        pwdLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        pwdLabel.setForeground(new Color(75, 85, 99));
        pwdLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.add(pwdLabel);
        section.add(Box.createVerticalStrut(12));

        // 旧密码
        oldPasswordField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32));
        oldPasswordField.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.add(createCompactFieldPanel("旧密码", oldPasswordField));
        section.add(Box.createVerticalStrut(8));

        // 新密码
        newPasswordField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32));
        newPasswordField.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.add(createCompactFieldPanel("新密码", newPasswordField));
        section.add(Box.createVerticalStrut(8));

        // 确认密码
        confirmPasswordField.setMaximumSize(new Dimension(Integer.MAX_VALUE, 32));
        confirmPasswordField.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.add(createCompactFieldPanel("确认密码", confirmPasswordField));
        section.add(Box.createVerticalStrut(15));

        // 修改密码按钮
        JPanel pwdButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        pwdButtonPanel.setOpaque(false);
        changePasswordButton.setPreferredSize(new Dimension(120, 32));
        pwdButtonPanel.add(changePasswordButton);
        section.add(pwdButtonPanel);

        return section;
    }

    /**
     * 创建简化的信誉分部分（只显示分数/总分）
     */
    private JPanel createSimpleCreditSection() {
        JPanel section = new JPanel();
        section.setLayout(new BoxLayout(section, BoxLayout.Y_AXIS));
        section.setOpaque(false);

        // 紧凑的信誉分和等级显示（一行）
        JPanel compactPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
        compactPanel.setOpaque(false);

        JLabel currentScoreLabel = new JLabel("信誉分：");
        currentScoreLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        currentScoreLabel.setForeground(new Color(75, 85, 99));

        creditScoreLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 18));
        creditScoreLabel.setForeground(new Color(99, 102, 241));

        JLabel totalScoreLabel = new JLabel("/150");
        totalScoreLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        totalScoreLabel.setForeground(new Color(100, 116, 139));

        JLabel separatorLabel = new JLabel("  |  ");
        separatorLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        separatorLabel.setForeground(new Color(200, 200, 200));

        JLabel levelTextLabel = new JLabel("等级：");
        levelTextLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        levelTextLabel.setForeground(new Color(75, 85, 99));

        creditLevelLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 11));
        creditLevelLabel.setForeground(new Color(34, 197, 94));
        creditLevelLabel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(34, 197, 94), 1),
                BorderFactory.createEmptyBorder(1, 6, 1, 6)));

        compactPanel.add(currentScoreLabel);
        compactPanel.add(creditScoreLabel);
        compactPanel.add(totalScoreLabel);
        compactPanel.add(separatorLabel);
        compactPanel.add(levelTextLabel);
        compactPanel.add(creditLevelLabel);

        section.add(compactPanel);

        return section;
    }

    /**
     * 创建信誉分历史记录部分
     */
    private JPanel createCreditHistorySection() {
        JPanel section = new JPanel();
        section.setLayout(new BoxLayout(section, BoxLayout.Y_AXIS));
        section.setOpaque(false);

        // 历史记录标题（无额外间距）
        JLabel historyLabel = new JLabel("信誉分历史记录：");
        historyLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        historyLabel.setForeground(new Color(75, 85, 99));
        historyLabel.setAlignmentX(Component.LEFT_ALIGNMENT);
        section.add(historyLabel);
        // 不添加任何垂直间距

        // 历史记录列表容器
        creditHistoryContainer = new JPanel(); // 保存引用
        creditHistoryContainer.setLayout(new BoxLayout(creditHistoryContainer, BoxLayout.Y_AXIS));
        creditHistoryContainer.setOpaque(false);
        creditHistoryContainer.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 创建滚动面板用于历史记录（增加高度，几乎占满页面）
        JScrollPane scrollPane = new JScrollPane(creditHistoryContainer);
        scrollPane.setPreferredSize(new Dimension(0, 500));
        scrollPane.setMaximumSize(new Dimension(Integer.MAX_VALUE, 500));
        scrollPane.setBorder(BorderFactory.createLineBorder(new Color(229, 231, 235), 1));
        scrollPane.setBackground(Color.WHITE);
        scrollPane.getViewport().setBackground(Color.WHITE);
        scrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);

        // 动态加载信誉分历史记录
        loadCreditHistory(creditHistoryContainer);

        section.add(scrollPane);

        return section;
    }

    /**
     * 加载信誉分历史记录
     */
    private void loadCreditHistory(JPanel container) {
        try {
            container.removeAll();

            LocalDate startDate = LocalDate.now().minusMonths(1);
            LocalDate endDate = LocalDate.now();
            List<CreditLog> creditLogs = attendanceController.getUserCreditLogs(currentUser.getUserId(), startDate,
                    endDate);

            if (creditLogs.isEmpty()) {
                JLabel placeholder = new JLabel("暂无信誉分变更记录");
                placeholder.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
                placeholder.setForeground(new Color(156, 163, 175));
                placeholder.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
                placeholder.setHorizontalAlignment(JLabel.CENTER);
                container.add(placeholder);
            } else {
                // 只显示最近10条记录
                int maxRecords = Math.min(creditLogs.size(), 10);
                for (int i = 0; i < maxRecords; i++) {
                    CreditLog log = creditLogs.get(i);
                    JPanel logPanel = createCreditLogItem(log);
                    container.add(logPanel);
                    if (i < maxRecords - 1) {
                        container.add(Box.createVerticalStrut(8));
                    }
                }
            }

            container.revalidate();
            container.repaint();

        } catch (Exception e) {
            e.printStackTrace();
            container.removeAll();
            JLabel errorLabel = new JLabel("加载信誉分记录失败");
            errorLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
            errorLabel.setForeground(new Color(239, 68, 68));
            errorLabel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
            errorLabel.setHorizontalAlignment(JLabel.CENTER);
            container.add(errorLabel);
            container.revalidate();
            container.repaint();
        }
    }

    /**
     * 创建信誉分记录项
     */
    private JPanel createCreditLogItem(CreditLog log) {
        JPanel panel = new JPanel(new BorderLayout(12, 0));
        panel.setOpaque(true);
        panel.setBackground(Color.WHITE);

        // 添加细微的外边框和减少内边距
        panel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(12, 15, 12, 15)));

        // 设置固定的较小高度
        panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, 60));
        panel.setPreferredSize(new Dimension(0, 60));

        // 左侧：详细信息
        JPanel leftPanel = new JPanel(new BorderLayout(0, 4));
        leftPanel.setOpaque(false);

        // 原因标签 - 增大字体并添加更多详细信息
        String detailedReason = log.getReason();
        if (log.getScoreChange() > 0) {
            detailedReason = detailedReason + " (获得奖励)";
        } else {
            detailedReason = detailedReason + " (扣除信誉分)";
        }

        JLabel reasonLabel = new JLabel(detailedReason);
        reasonLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14)); // 增大字体
        reasonLabel.setForeground(new Color(30, 41, 59)); // 更深的颜色

        // 时间和位置信息 - 增大字体并添加更多信息
        String timeAndInfo = log.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")) +
                "  •  " + log.getLogTypeText();
        JLabel timeLabel = new JLabel(timeAndInfo);
        timeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13)); // 增大字体
        timeLabel.setForeground(new Color(75, 85, 99)); // 稍深一点的颜色

        leftPanel.add(reasonLabel, BorderLayout.NORTH);
        leftPanel.add(timeLabel, BorderLayout.SOUTH);

        // 右侧：变化分数 - 增大字体和添加更多信息
        JPanel rightPanel = new JPanel(new BorderLayout());
        rightPanel.setOpaque(false);

        JLabel changeLabel = new JLabel();
        int scoreChange = log.getScoreChange();
        if (scoreChange > 0) {
            changeLabel.setText("+" + scoreChange + " 分");
            changeLabel.setForeground(new Color(34, 197, 94));
        } else {
            changeLabel.setText(scoreChange + " 分");
            changeLabel.setForeground(new Color(239, 68, 68));
        }
        changeLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 15)); // 增大字体
        changeLabel.setHorizontalAlignment(JLabel.CENTER);

        // 添加变化前信誉分信息 - 通过计算得到
        int scoreBefore = log.getScoreAfter() - log.getScoreChange();
        JLabel beforeLabel = new JLabel(scoreBefore + " → " + log.getScoreAfter());
        beforeLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 11));
        beforeLabel.setForeground(new Color(107, 114, 128));
        beforeLabel.setHorizontalAlignment(JLabel.CENTER);

        rightPanel.add(changeLabel, BorderLayout.CENTER);
        rightPanel.add(beforeLabel, BorderLayout.SOUTH);

        panel.add(leftPanel, BorderLayout.CENTER);
        panel.add(rightPanel, BorderLayout.EAST);

        return panel;
    }

    /**
     * 手动刷新数据
     */
    private void refreshData() {
        SwingUtilities.invokeLater(() -> {
            try {
                // 从用户列表中获取最新的用户信息
                List<User> allUsers = userController.getAllUsers();
                User refreshedUser = allUsers.stream()
                        .filter(u -> u.getUserId() == currentUser.getUserId())
                        .findFirst()
                        .orElse(null);

                if (refreshedUser != null) {
                    this.currentUser = refreshedUser;
                    loadUserInfo(); // 重新加载基本信息到表单
                }

                // 重新加载信誉分和考勤信息
                loadCreditAndAttendanceInfo();

                // 直接刷新信誉分历史记录（使用保存的引用）
                if (creditHistoryContainer != null) {
                    loadCreditHistory(creditHistoryContainer);
                }

                // 刷新UI显示
                revalidate();
                repaint();

                JOptionPane.showMessageDialog(this, "数据刷新成功!", "提示", JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception e) {
                e.printStackTrace();
                JOptionPane.showMessageDialog(this, "数据刷新失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
}
